package main

import (
	"SQLi/model"
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

type UserRepository struct {
	db *sql.DB
}

func NewUserRepository(db *sql.DB) *UserRepository {
	return &UserRepository{db: db}
}

func GetDB(username, password string) (*sql.DB, error) {
	//ALTER DATABASE go_sec_labs CHARACTER SET = gbk COLLATE = gbk_chinese_ci;
	//ALTER TABLE `user` CONVERT TO CHARACTER SET gbk COLLATE gbk_chinese_ci;
	db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(localhost:3306)/go_sec_labs2?charset=gbk&interpolateParams=true", username, password))
	if err != nil {
		return nil, err
	}

	return db, nil
}

func (repo *UserRepository) SelectByName(name string) ([]model.User, error) {
	query := "SELECT id, name, age, sex, password FROM user WHERE name = ?"
	rows, err := repo.db.Query(query, name)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	defer rows.Close()

	return repo.orm2User(rows)
}

func (repo *UserRepository) orm2User(rows *sql.Rows) ([]model.User, error) {
	var users []model.User
	for rows.Next() {
		var user model.User
		if err := rows.Scan(&user.Id, &user.Name, &user.Age, &user.Sex, &user.Password); err != nil {
			log.Printf("Failed to scan row: %v", err)
			continue
		}
		users = append(users, user)
	}

	if err := rows.Err(); err != nil {
		log.Printf("Row iteration error: %v", err)
		return nil, err
	}

	return users, nil
}

func main() {
	// 初始化数据库连接
	db, err := GetDB("root", "111111")
	if err != nil {
		log.Fatalf("Get db error: %v", err)
	}
	defer db.Close() // 确保程序结束时关闭数据库连接

	userRepo := NewUserRepository(db)

	users, err := userRepo.SelectByName("\xDF' or 1=1 -- ")
	if err != nil {
		log.Fatalf("SelectByName error: %v", err)
	}
	for _, user := range users {
		fmt.Println(user)
	}
}